package utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    //1.私有化构造方法
    private JDBCUtils(){}
    //2.声明所需配置变量

    private static Connection con;
    private static DataSource dataSource;
    //3.提供静态代码块,读取配置文件信息为变量赋值，注册驱动
    static {
        try {
            //1.创建c3p0数据库连接池对象
            dataSource = new ComboPooledDataSource();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //4.获取数据库连接的方法
    public static Connection getConnection(){
        try {
            //2.通过连接池对象获取数据库连接
            con = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    //5.释放资源方法
    public static void close(Connection con , PreparedStatement stat, ResultSet rs){
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con , PreparedStatement stat){
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

